//  封装axios
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
import router from '@/router'

const requests = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 50000
})

// 配置拦截器
// axios请求拦截器
requests.interceptors.request.use(config => {
  // 获取到token信息
  const userStore = useUserStore()
  const token = userStore.userInfo.token 

  if (token) { 
    config.headers.Authorization = `Bearer ${token}`
  }


  return config
}, e => Promise.reject(e))

// axios响应式拦截器
requests.interceptors.response.use(res => res.data, e => {
  // 统一错误提示
  ElMessage({
    type: 'warning',
    message: e.response.data.message
  })

  const userStore = useUserStore()
  // 401失效token处理
  // 1.清除本地用户数据
  // 2.跳转到登录页面
  if (e.response.status === 401) {
    // 删除token信息
    userStore.logout()
    router.push('/login')
  }
  return Promise.reject(e)
})

export default requests